package com.woniuxy.hrp.web;

import com.woniuxy.hrp.Vo.NatVo;
import com.woniuxy.hrp.entity.Hospital;
import com.woniuxy.hrp.entity.Nat;
import com.woniuxy.hrp.entity.Patient;
import com.woniuxy.hrp.entity.Reservation;
import com.woniuxy.hrp.exception.NatException;
import com.woniuxy.hrp.mapper.ReservationMapper;
import com.woniuxy.hrp.security.JwtUtil;
import com.woniuxy.hrp.service.HospitalService;
import com.woniuxy.hrp.service.NatService;
import com.woniuxy.hrp.unityhandler.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@RestController
@RequestMapping("/api/v1/nat")
public class NatControll {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private NatService natService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private ReservationMapper reservationMapper;

    @PostMapping("/add")
    public ResponseEntity add(@RequestBody Reservation reservation, @RequestHeader String jwt) throws NatException {
        if(reservation.getNat().getId()==0){
            throw new NatException("未输入医院");
        }
        reservation.setStatus("n");
        SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        reservation.setDatetime(defaultFormat.format(new Date()));
        Patient patient = new Patient();

        patient.setId((Integer) jwtUtil.getInfo(jwt, "id"));
        reservation.setPatient(patient);
        reservationMapper.add(reservation);

        return new ResponseEntity("200", "success", "加入的id为" + reservation.getId());
    }

    @PostMapping("/selehospital")
    public ResponseEntity seleHospital(@RequestBody Nat nat) {
        List<Hospital> hospitals = hospitalService.seleAll();
        List<NatVo> natVos = new ArrayList<>();
        hospitals.forEach(d -> {
            natService.seleAll().forEach(r -> {
                if (r.getHospital().getId() == d.getId()) {
                    NatVo natVo = new NatVo();
                    natVo.setHospitalname(d.getName());
                    natVo.setFee(r.getFee());
                    natVo.setNatid(r.getId());
                    natVos.add(natVo);
                }
            });
        });
        return new ResponseEntity("200", "success", natVos);
    }

    @PostMapping("/unpre")
    public ResponseEntity unpre(@RequestHeader String jwt) {
        reservationMapper.deleNat((Integer) jwtUtil.getInfo(jwt, "id"));
        return new ResponseEntity("200", "success","删除成功");
    }
}
